#!/usr/bin/python 
#Author:eager.yu
#Email: sanguren@qq.com

from Cloudstack_option import Cloudstack_option
import sys,re
import getopt

def usage():
    print "help-------------------------------------------------------------------"
    print "it is just get running instances"
    print "get the instance list of account"
    print "command: python getAllinstance.py -u admin"
    print "get all instances list"
    print "command: python getAllinstance.py"
    print "------------------------------------------------------------------------"

def main():
    account=""
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hu:",["help", "account="])
    except getopt.GetoptError as err:
        print str(err) 
        usage()
        sys.exit(2)
    for o,a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit(0)
        elif o in ("-u", "--account"):
            account=a
        else:
            assert False, "unhandled option"
            
    cs=Cloudstack_option()
    accounts=cs.get_all_account()
    acc=[]
    for i in accounts:
        acc.append(i["name"])
    if not account in acc and account != "":
        print "the account not find in cloudstack"
        sys.exit()
    instances=cs.get_all_instance(account)
    for i in instances:
        print "%s:%s    %s:%s     %s:%s    %s:%s" %("name",str(i["name"]),
                                    "ipaddress",str(i["nic"][0]["ipaddress"]),
                                    "instanaceid",str(i["id"]),
                                    "status",str(i["state"])
                                     )
    sys.exit(0)


if __name__ == "__main__":
    main()